<template>
  <div>
    <p>
      <button class="btn btn-white btn-default btn-round" @click="add()">
        <i class="ace-icon fa fa-edit"></i>
        新增
      </button>
      &nbsp;
      <button class="btn btn-white btn-default btn-round" @click="list(1)">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
    </p>

    <pagination ref="pagination" :list="list"></pagination>
    <div class="row">
      <div v-for="course in courses" class="col-md-4">
        <div class="thumbnail search-thumbnail">
          <img v-show="!course.image" class="media-object" src="/admin/static//image/demo-course.jpg" />
          <img v-show="course.image" class="media-object" v-bind:src="course.image" />
          <div class="caption">
            <div class="clearfix">
              <span class="pull-right label label-primary info-label">
                {{COURSE_LEVEL | optionKV(course.level)}}
              </span>
              <span class="pull-right label label-primary info-label">
                {{COURSE_CHARGE | optionKV(course.charge)}}
              </span>
              <span class="pull-right label label-primary info-label">
                {{COURSE_STATUS | optionKV(course.status)}}
              </span>
            </div>

            <h3 class="search-title">
              <a href="#" class="blue">{{course.name}}</a>
            </h3>

            <div v-for="teacher in teachers.filter(t=>{return t.id===course.teacherId})" class="profile-activity clearfix">
              <div>
                <img v-show="!teacher.image" class="pull-left" src="/ace-master/assets/images/avatars/avatar5.png">
                <img v-show="teacher.image" class="pull-left" v-bind:src="teacher.image">
                <a class="user" href="#"> {{teacher.name}} </a>
                <br>
                {{teacher.position}}
              </div>
            </div>

            <p>
              <span class="blue bolder bigger-150">{{course.price}}&nbsp;<i class="fa fa-rmb"></i></span>&nbsp;
            </p>
            <p>{{course.summary}}</p>
            <p>
              <span class="badge badge-info">{{course.id}}</span>&nbsp;
              <span class="badge badge-info">排序：{{course.sort}}</span>&nbsp;
              <span class="badge badge-info">时长：{{course.time | formatSecond}}</span>
            </p>
            <p>
              <button v-on:click="toChapter(course)" class="btn btn-white btn-xs btn-info btn-round">
                大章
              </button>&nbsp;
              <button v-on:click="toContent(course)" class="btn btn-white btn-xs btn-info btn-round">
                内容
              </button>&nbsp;
              <button v-on:click="openSortModal(course)" class="btn btn-white btn-xs btn-info btn-round">
                排序
              </button>&nbsp;
              <button v-on:click="edit(course)" class="btn btn-white btn-xs btn-info btn-round">
                编辑
              </button>&nbsp;
              <button v-on:click="del(course.id)" class="btn btn-white btn-xs btn-warning btn-round">
                删除
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增与更新Modal -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">课程表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">分类</label>
                <div class="col-sm-10">
                  <ul id="tree" class="ztree"></ul>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">封面</label>
                <div class="col-sm-10">
                  <big-file :text="'上传封面'"
                        :input-id="'cover-upload'"
                        :suffixs="['jpg', 'jpeg', 'png', 'mp4']"
                        :use="FILE_USE.COURSE.key"
                        :after-upload="afterUpload"></big-file>
                  <div v-show="course.image" class="row">
                    <div class="col-md-6">
                      <img :src="course.image" class="img-responsive">
                    </div>
                  </div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.name">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">讲师</label>
                <div class="col-sm-10">
                  <select v-model="course.teacherId" class="form-control">
                    <option v-for="teacher in teachers" :value="teacher.id">{{teacher.name}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">概述</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.summary">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时长</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.time">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">价格（元）</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.price">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">级别</label>
                <div class="col-sm-10">
                  <select v-model="course.level" class="form-control">
                    <option v-for="o in COURSE_LEVEL" :value="o.key">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费</label>
                <div class="col-sm-10">
                  <select v-model="course.charge" class="form-control">
                    <option v-for="o in COURSE_CHARGE" :value="o.key">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">状态</label>
                <div class="col-sm-10">
                  <select v-model="course.status" class="form-control">
                    <option v-for="o in COURSE_STATUS" :value="o.key">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">报名数</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.enroll">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="course.sort" disabled>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save()">保存</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 排序Modal -->
    <div id="course-sort-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">排序</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">当前排序</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="sort.oldSort" name="oldSort" disabled>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">新排序</label>
                <div class="col-sm-10">
                  <input class="form-control" v-model="sort.newSort" name="newSort">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="updateSort()">
              <i class="ace-icon fa fa-plus blue"></i>
              更新排序
            </button>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import Pagination from "../../components/pagination"
  import BigFile from  '../../components/big-file'
  import File from  '../../components/file'

  export default {
    name: "business-course",
    components: {Pagination, BigFile, File},
    data() {
      return {
        course: {
          id: null,
          name: null,
          teacherId: null,
          summary: null,
          time: null,
          price: null,
          image: null,
          level: null,
          charge: null,
          status: null,
          enroll: null,
          sort: null,
          createdAt: null,
          updatedAt: null,
        },
        courses: [],
        COURSE_LEVEL: COURSE_LEVEL,
        COURSE_CHARGE: COURSE_CHARGE,
        COURSE_STATUS: COURSE_STATUS,
        categorys: [],
        tree: {},
        sort: {
          id: '',
          oldSort: 0,
          newSort: 0
        },
        teachers: [],
        FILE_USE: FILE_USE,
        files: []
      }
    },
    mounted() {
      let _this = this
      _this.allCategory()
      _this.allTeacher()
      _this.list(1)
    },
    methods: {
      /**
       * 获取课程（分页）
       * @param page
       */
      list(page) {
        let _this = this

        Loading.show()

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/course/list', {
          page: page,
          size: _this.$refs.pagination.size
        }).then((resp) => {
          if (resp.data.success) {
            _this.courses = resp.data.content.list
            _this.$refs.pagination.render(page, resp.data.content.total)

            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 添加课程（显示模态框）
       */
      add() {
        let _this = this
        _this.course = {
          id: null,
          name: null,
          summary: null,
          time: null,
          price: null,
          image: null,
          level: null,
          charge: null,
          status: null,
          enroll: null,
          sort: _this.$refs.pagination.total + 1,  // 新增时排序应该是总条数加1
          createdAt: null,
          updatedAt: null,
        }
        //  新增时所有节点都是未被选中的状态
        _this.tree.checkAllNodes(false)
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 编辑课程（显示模态框）
       */
      edit(course) {
        let _this = this
        //  Object.assign(target, source)方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target)
        Object.assign(_this.course, course)
        //  查找被编辑的课程的分类
        _this.listCategory(course.id)
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 根据课程id查找其分类,并渲染到zTree上
       */
      listCategory(courseId) {
        let _this = this

        Loading.show()

        _this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/course/list-category/' + courseId).then((resp) => {
          if (resp.data.success) {
            Loading.hide()

            let categorys = resp.data.content

            //  勾选查询到的分类
            _this.tree.checkAllNodes(false)
            for (let i =0; i < categorys.length; i++) {
              //  查找id为categorys[i].categoryId的节点
              let node = _this.tree.getNodeByParam('id', categorys[i].categoryId)
              _this.tree.checkNode(node, true)
            }
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 保存课程
       */
      save() {
        let _this = this

        //  保存校验
        if (1 != 1
          || !Validator.require(_this.course.name, "名称")
          || !Validator.length(_this.course.name, "名称", 1, 50)
          || !Validator.length(_this.course.summary, "概述", 1, 2000)
          || !Validator.length(_this.course.image, "封面", 1, 100)
        ) {
          return;
        }

        //  获得zTree里被选择的节点
        let categorys =  _this.tree.getChangeCheckedNodes()
        if (Tool.isEmpty(categorys)) {
          Toast.warning('请选择分类!')
          return
        }
        _this.course.categorys = categorys;

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/course/save', _this.course).then((resp) => {
          if (resp.data.success) {
            //  关闭模态框
            $("#form-modal").modal('hide')
            //  刷新表格
            _this.list(1)
            Toast.success('保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 删除课程（根据id）
       * @param id
       */
      del(id) {
        let _this = this
        Confirm.show('删除课程后不可恢复，是否确认删除？', () => {
          _this.$axios.delete(process.env.VUE_APP_SERVER + '/business/admin/course/delete/' + id).then((resp) => {
            if (resp.data.success) {
              //  刷新表格
              _this.list(1)
              Toast.success('删除成功！')
            }
          })
        })
      },

      /**
       * 跳转到大章
       */
      toChapter(course) {
        let _this = this
        SessionStorage.set(SESSION_KEY_COURSE, course)
        _this.$router.push('/business/chapter')
      },

      /**
       * 获取所有分类
       */
      allCategory() {
        let _this = this
        _this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/category/all').then((resp) => {
          if (resp.data.success) {
            _this.categorys = resp.data.content

            //  初始化zTree
            _this.initTree()
          }
        })
      },

      /**
       * 初始化zTree, 模板在zTree自带的demo里
       */
      initTree() {
        let _this = this
        let setting = {
          check: {
            enable: true
          },
          data: {
            simpleData: {
              idKey: 'id',
              pIdKey: 'parent', // 指明父节点在数据库里的名称, zTree默认叫pId
              rootPId: '00000000',
              enable: true
            }
          }
        };

        let zNodes = _this.categorys;
        _this.tree = $.fn.zTree.init($("#tree"), setting, zNodes);

        //  展开所有节点
        //_this.tree.expandAll(true)

      },

      /**
       * 显示富文本编辑框的模态框
       * @param course
       */
      editContent(course) {
        let _this = this
        let id = course.id
        _this.course = course
        //  初始化富文本框
        $("#content").summernote({
          focus: true,
          height: 300
        })
        //  每次点开内容, 先清空历史文本
        $("#content").summernote('code', '')
        //  加载内容文件列表
        _this.listContentFiles(id)

        Loading.show()

        _this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/course/find-content/' + id).then((resp) => {
          if (resp.data.success) {
            Loading.hide()

            if (resp.data.success) {
              //  把展示富文本编辑框的模态框设置成, 点击框外不会自动关闭模态框
              $("#course-content-modal").modal({backdrop: 'static', keyboard: false})
              if (resp.data.content) {
                $("#content").summernote('code', resp.data.content.content)
              }
            } else {
              Toast.warning(resp.message)
              Loading.hide()
            }
          }
        })
      },

      /**
       * 保存课程内容
       */
      saveContent() {
        let _this = this
        //  获取富文本框的内容的html
        let content = $('#content').summernote('code')
        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/course/save-content/', {
          id: _this.course.id,
          content: content
        }).then((resp) => {
          if (resp.data.success) {
            Toast.success('内容保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 显示排序模态框
       * @param course
       */
      openSortModal(course) {
        let _this = this
        _this.sort = {
          id: course.id,
          oldSort: course.sort,
          newSort: course.sort
        }
        $("#course-sort-modal").modal('show')
      },

      /**
       * 更新排序
       */
      updateSort() {
        let _this = this
        if (_this.sort.newSort === _this.sort.oldSort) {
          Toast.warning('排序没有变化')
          return
        }

        Loading.show()

        _this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/course/sort/', _this.sort).then((resp) => {
          if (resp.data.success) {
            Toast.success('更新成功！')
            $("#course-sort-modal").modal('hide')
            _this.list(1)
          } else {
            Toast.error('更新排序失败')
            Loading.hide()
          }
        })
      },

      /**
       * 获取所有老师
       */
      allTeacher() {
        let _this = this
        _this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/teacher/all').then((resp) => {
          if (resp.data.success) {
            _this.teachers = resp.data.content
          }
        })
      },

      /**
       * 上传文件组件的回调函数
       * @param resp
       */
      afterUpload(resp) {
        let _this = this
        let image = resp.data.content.path
        _this.course.image = image
      },

      /**
       * 跳转到内容
       */
      toContent(course) {
        let _this = this
        SessionStorage.set(SESSION_KEY_COURSE, course)
        _this.$router.push('/business/content')
      }
    }
  }
</script>

<style scoped>
  .caption h3 {
    font-size: 20px;
  }

  @media (max-width: 1199px) {
    .caption h3 {
      font-size: 16px;
    }
  }
</style>